package com.dxy.lc.manager;

import com.dxy.lc.cache.ExpiringCache;
import com.dxy.lc.cache.ICache;
import com.dxy.lc.mapper.DeptMapper;
import com.dxy.lc.mapper.UserMapper;
import com.dxy.lc.model.entity.Dept;
import com.dxy.lc.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class DeptCacheManager {

    public static DeptCacheManager INSTANCE;

    private ICache<String, Dept> deptCache;

    @Autowired
    private DeptMapper deptMapper;

    @Value("${cache.conf.dept-cache-duration:1}")
    private long deptCacheDuration;

    @PostConstruct
    public void init(){
        deptCache = new ExpiringCache<String, Dept>()
                .setDuration(deptCacheDuration)
                .setTimeUnit(TimeUnit.HOURS)
                .setLoader(this::selectFromDb);
        DeptCacheManager.INSTANCE = this;
    }

    @PreDestroy
    public void destroy(){
        ExpiringCache.shutdown();
    }

    private Dept selectFromDb(String id) {
        log.debug("======> dept cache select from db, userId: " + id + " <======");
        return deptMapper.selectById(id);
    }

    public Dept getById(String id){
        return deptCache.get(id);
    }

    public void removeById(String id){
        deptCache.remove(id);
    }
}
